# -*- coding: utf-8 -*-
import json
import os
from alibabacloud_tea_openapi_sse import models as open_api_models
from alibabacloud_tea_openapi_sse.client import Client as OpenApiClient
from alibabacloud_tea_util_sse import models as util_models

class LightApp:
    def __init__(self) -> None:
        self.access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        self.access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        self.workspace_id = os.environ['WORKSPACE_ID']
        self.endpoint = 'quanmiaolightapp.cn-beijing.aliyuncs.com'
        self._client = None
        self._api_info = self._create_api_info()
        self._runtime = util_models.RuntimeOptions(read_timeout=1000 * 100)
        self._client = self._create_client(self.access_key_id, self.access_key_secret, self.endpoint)

    def _create_client(
            self,
            access_key_id: str,
            access_key_secret: str,
            endpoint: str,

    ) -> OpenApiClient:
        config = open_api_models.Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret,
            endpoint=endpoint,
        )
        return OpenApiClient(config)

    def _create_api_info(self) -> open_api_models.Params:
        params = open_api_models.Params(
            action='RunVideoAnalysis',
            version='2024-08-01',
            protocol='HTTPS',
            method='POST',
            auth_type='AK',
            style='RPC',
            pathname='/' + self.workspace_id + '/quanmiao/lightapp/runVideoAnalysis',
            req_body_type='json',
            body_type='sse'
        )
        return params

    async def run_video_analysis(self, run_video_analysis_param):
        param = json.loads(run_video_analysis_param) if run_video_analysis_param else {}
        request = open_api_models.OpenApiRequest(body=param)
        sse_receiver = self._client.call_sse_api_async(params=self._api_info, request=request, runtime=self._runtime)
        async for res in sse_receiver:
            data = json.loads(res.get('event').data)
            if data.get('payload', {}).get('output', {}).get('resultJsonFileUrl'):
                description = data['payload']['output']['videoGenerateResults'][0]['text']
                return description